package com.zpark.spring_01.factory;

import java.io.InputStream;
import java.util.*;

/**
 * Bean工厂
 */
public class BeanFactory {
    private static Properties properties = new Properties();

    // 定义存放bean的容器
    private static Map<String, Object> beans = new HashMap<>();

    static {
        try {
            InputStream stream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.properties");
            properties.load(stream);

            // 读取配置文件，将对象创建号之后存放到容器当中
            Enumeration<?> names = properties.propertyNames(); // 获取配置文件当中的所有key
            while (names.hasMoreElements()) {
                String key = names.nextElement().toString();
                String value = properties.getProperty(key);

                // 创建对象
                Object bean = Class.forName(value).newInstance();
                // 将bean存放到容器
                beans.put(key, bean);
            }
        } catch(Exception e) {

        } finally {

        }
    }

    /**
     * 根据bean的名字获取bean对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }

//    /**
//     * 根据bean的名字获取bean对象
//     * @param beanName
//     * @return
//     */
//    public static Object getBean(String beanName) {
//        String name = properties.getProperty(beanName);
//        Object o = null;
//        try {
//            o = Class.forName(name).newInstance();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//        return o;
//    }
}
